package com.baidu.aip.fl.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.aip.fl.R;
import com.baidu.aip.fl.utils.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 选择用户
 * Created by Administrator on 2018/10/9.
 */

public class UserDialog extends Dialog {

    private Context mContext;
    private boolean mIsAdd = false;
    private String mUserName;
    private Button regBtn;

    private UserAdapter mAdapter;
    private JSONArray mDataArray = new JSONArray();

    private Handler handler = new Handler(Looper.getMainLooper());

    private View.OnClickListener mOnClickListener;

    public UserDialog(@NonNull Context context,boolean isAdd,String userName,JSONArray dataArray,View.OnClickListener onClickListener) {
        super(context);
        this.mContext = context;
        this.mIsAdd = isAdd;
        this.mUserName = userName;
        this.mDataArray = dataArray;
        this.mOnClickListener = onClickListener;

        init();
    }

    private void init() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_user,null,false);

        ListView lv = (ListView) view.findViewById(R.id.user_lv);
        lv.setAdapter(mAdapter = new UserAdapter());

        regBtn = (Button) view.findViewById(R.id.user_add);
        regBtn.setVisibility(mIsAdd ? View.VISIBLE : View.GONE);
        regBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reg();
            }
        });

        setContentView(view);

        WindowManager.LayoutParams wmlp = getWindow().getAttributes();
        wmlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wmlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(wmlp);
    }

    private void reg() {
        RequestBody requestBody = new FormBody.Builder()
                .add("staffName",mUserName)
                .build();
        //注册
        HttpUtil.getInstance().post("staff/staffReg", requestBody, new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext,"注册失败：" + e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String shipStaffId = null;
                if (response != null && response.code() == 200) {
                    try {
                        String res = response.body().string();
                        Log.e("onResponse",res);
                        JSONObject jsonObject = new JSONObject(res);
                        if (jsonObject.has("shipStaffId")) {
                            shipStaffId = jsonObject.getString("shipStaffId");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                final String finalShipStaffId = shipStaffId;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (TextUtils.isEmpty(finalShipStaffId)) {
                            Toast.makeText(mContext,"注册失败",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        regBtn.setTag(finalShipStaffId);
                        mOnClickListener.onClick(regBtn);
                    }
                });
            }
        });
    }

    class UserAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mDataArray.length();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            TextView tv = (TextView) LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_1, null, false);
            try {
                JSONObject dataObj = mDataArray.getJSONObject(i);
                if (dataObj.has("staffName") && dataObj.has("shipStaffId")) {
                    String staffName = dataObj.getString("staffName");
                    String shipStaffId = dataObj.getString("shipStaffId");
                    String staffIdCard = dataObj.has("staffIdCard") ? dataObj.getString("staffIdCard") : "";
                    if (TextUtils.isEmpty(staffIdCard) || "null".equals(staffIdCard)) {
                        staffIdCard = "无";
                    }
                    tv.setText("姓名：" + staffName + "\n身份证号：" + staffIdCard);

                    tv.setTag(shipStaffId);
                    tv.setOnClickListener(mOnClickListener);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return tv;
        }
    }

}
